package nl.jjsoft.airlock.view.presenters
{
	import com.adobe.utils.StringUtil;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.filesystem.File;
	import flash.net.FileFilter;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	
	import nl.jjsoft.airlock.AirLockConstants;
	import nl.jjsoft.airlock.controller.ILoginController;
	import nl.jjsoft.airlock.controller.SafeController;
	import nl.jjsoft.airlock.domain.Model;
	import nl.jjsoft.airlock.domain.Session;
	import nl.jjsoft.airlock.event.ApplicationEvent;
	import nl.jjsoft.airlock.utils.DbUtils;
	import nl.jjsoft.airlock.utils.ResourceFactory;
	import nl.jjsoft.airlock.view.Login;
	
	public class LoginPresenter extends AbstractPresenter
	{
		[Inject]
		public var loginController:ILoginController;
		
		[Inject]
		public var safeController:SafeController;
		 
		[Inject]
		public var model:Model;
		
		[Inject]
		public var session:Session;
		
		[Inject]
		public var dbUtils:DbUtils;
		
		[Inject]
		public var resourceFactory:ResourceFactory;
		
		private const safeFilter:FileFilter = new FileFilter("Safe Files (*.safe)","*.safe;");
				
		public function LoginPresenter()
		{
			super(Login);
		}
		
		override protected function init():void {
			super.init();
			initFocus();
		}
		
		override protected function setViewListeners():void {
			registerEventHandler(view.newSafeButton, MouseEvent.CLICK, gotoSetupView);
			registerEventHandler(view.loginButton, MouseEvent.CLICK, loginToSafe);
			registerEventHandler(view.browseForSafe, MouseEvent.CLICK, browseOpenSafe);
		}
		
		/**
		* Since the AbstractViewMediator sets the view via Autowiring in Swiz,
		* we need to create a local getter to access the underlying, expected view
		* class type.
		*/
		public function get view():Login {
			return this._view as Login;
		}
		
		public function gotoSetupView():void {
			dispatcher.dispatchEvent(new ApplicationEvent(ApplicationEvent.DISPLAY_SETUP_VIEW, true));	
		}
		
		[Mediate(event="ApplicationEvent.DISPLAY_LOGIN_VIEW")]
		public function displayLoginView():void {	
			if (!loginController.dbExists(session.dbFilePath)){
				session.dbFilePath = "";
			}	
			model.selectedView = AirLockConstants.VIEW_LOGIN;
			
			initFocus();
		}
		
		public function loginToSafe():void {
			session.safeCombination = StringUtil.trim(view.safeKey.text);
			
			if (!loginController.isKeySecure(session.safeCombination)) {
				session.safeCombination = null;
				Alert.show(resourceFactory.getResource("error.wrongpw.caption"), resourceFactory.getResource("error.general.title"));
			} else {
				if (loginController.loginToPasswordDB(session.dbFilePath ,session.safeCombination)) {				
					dbUtils.setLastSelectedDB(session.dbFilePath);				
					var dbVersionUsing:String = safeController.getAppVersionFromDB();				
					if (dbVersionUsing != AirLockConstants.DB_VERSION){
						Alert.show(resourceFactory.getResource("error.dbversion.caption"), resourceFactory.getResource("error.general.title"));
					}	
					// TODO implement DB update script			
					model.groups = new ArrayCollection(safeController.getGroups());
					model.selectedView = AirLockConstants.VIEW_MAIN;					
				} else {
					session.safeCombination = null;
					Alert.show(resourceFactory.getResource("error.wrongpw.caption"), resourceFactory.getResource("error.general.title"));
				}
			}
		}

		public function browseOpenSafe():void {
			var safeFile:File = StringUtil.stringHasValue(session.dbFilePath) ? new File(session.dbFilePath) : File.documentsDirectory;
			safeFile.addEventListener(Event.SELECT, function (event:Event):void {
				var f:File = File(event.target);
				if (f.extension == null) {f.nativePath += AirLockConstants.DB_EXTENSION; }
				else if(f.extension != AirLockConstants.DB_EXTENSION.substr(1, AirLockConstants.DB_EXTENSION.length)) {
					Alert.show(resourceFactory.getResource("error.extension.caption"), resourceFactory.getResource("error.general.title"));
					return;
				}
				session.dbFilePath = f.nativePath;
			});
			safeFile.browseForOpen(resourceFactory.getResource("login.openexisting"), [safeFilter]);
		}
		
		private function initFocus() : void {
			if (view == null || view.safeLocation == null) return;
			
			if (view.safeLocation.length == 0)
				view.safeLocation.setFocus();
			else if (view.safeKey.length == 0)
				view.safeKey.setFocus();
			
		}
	}
}